package com.lishe.lishe.lishe.module.recharge.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.fynn.fluidlayout.FluidLayout;
import com.lishe.lishe.R;
import com.lishe.lishe.alipay.AliPayUtils;
import com.lishe.lishe.alipay.PayResult;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.me.http.HttpUserCenter;
import com.lishe.lishe.lishe.module.recharge.bean.IntegralObject;
import com.lishe.lishe.lishe.module.recharge.http.HttpPay;
import com.lishe.lishe.lishe.utils.AppUtils;
import com.lishe.lishe.lishe.utils.DecimalDigitsInputFilter;
import com.lishe.lishe.lishe.utils.FormatUtil;
import com.lishe.lishe.lishe.utils.ImeiUtil;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.net.BaseHttpLoader;
import com.lishe.lishe.net.BaseProtocal;
import com.lishe.lishe.net.NetAPI;
import com.lishe.lishe.net.ResultListener;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.bean.CreatePreOrderBean;
import com.lishe.lishe.retrofit.presenter.PayPresenter;
import com.lishe.lishe.wxapi.WXPayEntryActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import io.reactivex.Observable;
import okhttp3.ResponseBody;


/**
 * Created by lwa on 2017/8/21.
 * 积分充值
 */

public class RechargeIntegralActivity extends BaseActivity implements View.OnClickListener {

    private Button btnPay;
    private Button btnBack;
    private TextView texTitle;
    private TextView texRemainMoney;//余额
    private TextView texNeedPay;
    private LinearLayout moneylayout;
    private RelativeLayout alipayLayout;
    private RelativeLayout wxpayLayout;
    private FluidLayout integralFluLayou;
    private ImageView alipayImg;
    private ImageView wxpayImg;
    private EditText mEtMoney;
    private ImageView mImageRechargeRecord;
    private boolean isWXPay = false;//支付方式（支付宝，微信）
    private int rechargeIndex = -1;//选择充值积分的标志（-1未选择）
    private List<LinearLayout> integralButtons = new ArrayList<>();//积分按钮
    private List<IntegralObject> integralObjects = new ArrayList<>();//积分充值列表
    private String remainMoney = "0";//余额
    private IWXAPI iwxapi;
    private CreatePreOrderBean mPreOrderBean;

    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, RechargeIntegralActivity.class);
        activity.startActivity(intent);
    }

    public static void jumpForResult(Activity activity, int requstCode) {
        Intent intent = new Intent(activity, RechargeIntegralActivity.class);
        activity.startActivityForResult(intent, requstCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_integral);
        initView();
        searchRecharge();
        HttpUserCenter.getUserInfo(null, resposeUser);
        iwxapi = WXAPIFactory.createWXAPI(context, null);
        // 将该app注册到微信
        iwxapi.registerApp(Globals.WeiXin_appId);
        //注册微信回调广播
        registerBroad();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LoadingUtils.closeDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (receiver != null) unregisterReceiver(receiver);
    }

    private void registerBroad() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WXPayEntryActivity.action_success);
        filter.addAction(WXPayEntryActivity.action_cancle);
        filter.addAction(WXPayEntryActivity.action_faild);
        registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LoadingUtils.closeDialog();
            toast(intent.getStringExtra("result"));
            switch (intent.getAction()) {
                case WXPayEntryActivity.action_success:
                    if (mPreOrderBean != null) {
                        queryPayResult(mPreOrderBean.paymentId, isWXPay ? "2" : "1");
                    }
                    break;
            }
        }
    };

    private void queryPayResult(String paymentId, String type) {
        BaseHttpLoader http = new BaseHttpLoader(BaseProtocal.class, Globals.LISHE_URL) {
            @Override
            public Observable<ResponseBody> structureObservable(NetAPI api) {
                return api.queryPayResult(paymentId, type, ImeiUtil.getUniquePsuedoID(), Globals.getToken());
            }
        };
        http.executor(new ResultListener() {
            @Override
            public void onSuccess(BaseProtocal mBaseProtocal) {
                ToastUtil.showToast(RechargeIntegralActivity.this, "充值成功，积分已到账！");
                HttpUserCenter.getUserInfo(null, resposeUser);
            }

            @Override
            public void onFail(int errcode, String msg) {
                ToastUtil.showToast(RechargeIntegralActivity.this, msg);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(RechargeIntegralActivity.this, R.string.network_or_server_exception);
            }
        });
    }

    private void initView() {
        moneylayout = findViewById(R.id.moneylayout);
        moneylayout.setVisibility(View.GONE);
        btnPay = findViewById(R.id.btn_common_red);
        btnBack = findViewById(R.id.title_left_button);
        texTitle = findViewById(R.id.title_text_title);
        texTitle.setText(R.string.recharge_integral);
        texRemainMoney = findViewById(R.id.remain_money);
        texNeedPay = findViewById(R.id.need_pay);
        alipayLayout = findViewById(R.id.alipay_layout);
        wxpayLayout = findViewById(R.id.wxpay_layout);
        alipayImg = findViewById(R.id.alipay_seleced_img);
        wxpayImg = findViewById(R.id.wxpay_seleced_img);
        integralFluLayou = findViewById(R.id.integral_layout);
        mEtMoney = findViewById(R.id.money);
        mImageRechargeRecord = findViewById(R.id.title_rigth_image);
        integralButtons.clear();
        setlistener();

        mImageRechargeRecord.setVisibility(View.VISIBLE);
        mImageRechargeRecord.setImageResource(R.mipmap.jilu_icon);

    }

    private void showIntegral() {
        //---------------------积分按钮，动态加入-------------------
        for (int i = 0; i < integralObjects.size(); i++) {
            IntegralObject integralObject = integralObjects.get(i);
            View integralView = getLayoutInflater().inflate(R.layout.item_recharge_integral, null);
            final LinearLayout integral_layout = integralView.findViewById(R.id.integral_layout);
            integralButtons.add(integral_layout);
            TextView texRechargeMoney = integralView.findViewById(R.id.recharge_money);
            TextView texExtraMoney = integralView.findViewById(R.id.extra_money);
            int integral = Integer.valueOf(integralObjects.get(i).getRechargeAmount());
            texRechargeMoney.setText(integral * 100 + "");
            int exintegral = Integer.valueOf(integralObject.getPresentIntegral());
            if (exintegral > 0) {
                texExtraMoney.setText("加赠" + exintegral);
            } else {
                texExtraMoney.setVisibility(View.GONE);
            }

            integral_layout.setTag(i);
            integral_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mEtMoney.setText("");
                    int tag = (Integer) integral_layout.getTag();
                    double money = Double.parseDouble(integralObjects.get(tag).getRechargeAmount());
                    texNeedPay.setText("¥" + String.format("%.2f", money));
                    integral_layout.setBackgroundResource(R.mipmap.btn_selected_red);
                    ((TextView) (integralButtons.get(tag).getChildAt(0))).setTextColor(getResources().getColor(R.color.white));
                    ((TextView) (integralButtons.get(tag).getChildAt(1))).setTextColor(getResources().getColor(R.color.white));
                    if (rechargeIndex == -1) {
                        rechargeIndex = (Integer) integral_layout.getTag();
                    }
                    if (rechargeIndex != tag) {
                        ((TextView) (integralButtons.get(rechargeIndex).getChildAt(0))).setTextColor(getResources().getColor(R.color.color4138));
                        ((TextView) (integralButtons.get(rechargeIndex).getChildAt(1))).setTextColor(getResources().getColor(R.color.color4138));
                        integralButtons.get(rechargeIndex).setBackgroundResource(R.mipmap.btn_no_selected_red);
                        rechargeIndex = (Integer) integral_layout.getTag();
                    }
                }
            });
            if (i == 0) {
                integral_layout.performClick();
            }
            integralFluLayou.addView(integralView);
        }
    }

    private void setlistener() {
        btnBack.setOnClickListener(this);
        btnPay.setOnClickListener(this);
        alipayLayout.setOnClickListener(this);
        wxpayLayout.setOnClickListener(this);
        mImageRechargeRecord.setOnClickListener(this);
        mEtMoney.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2)});
        mEtMoney.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (rechargeIndex != -1) {
                    ((TextView) (integralButtons.get(rechargeIndex).getChildAt(0))).setTextColor(getResources().getColor(R.color.color4138));
                    ((TextView) (integralButtons.get(rechargeIndex).getChildAt(1))).setTextColor(getResources().getColor(R.color.color4138));
                    integralButtons.get(rechargeIndex).setBackgroundResource(R.mipmap.btn_no_selected_red);
                    texNeedPay.setText("¥0");
                    rechargeIndex = -1;
                }
                return false;
            }
        });

        mEtMoney.addTextChangedListener(new TextWatcher() {

            String outStr = "";

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                String edit = s.toString();
                outStr = edit;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String words = s.toString();
                if (!TextUtils.isEmpty(words)) {
                    if (!words.equals(".") && Double.parseDouble(words) >= 10000000) {
                        texNeedPay.setText("¥" + FormatUtil.numFormat(Double.parseDouble(outStr)));
                        mEtMoney.setText(outStr);
                        mEtMoney.setSelection(mEtMoney.getText().toString().length());
                    } else if (!words.equals(".")){
                        texNeedPay.setText("¥" + FormatUtil.numFormat(Double.parseDouble(words)));
                    }
                } else {
                    texNeedPay.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                /*String words = s.toString();
                if (!TextUtils.isEmpty(words)) {
                    if (!words.equals(".") && Double.parseDouble(words) >= 10000000) {
                        ToastUtil.showToast(RechargeIntegralActivity.this, outStr + ".......");
                        texNeedPay.setText("¥" + FormatUtil.numFormat(Double.parseDouble(outStr)));
                    } else if (!words.equals(".")){
                        texNeedPay.setText("¥" + FormatUtil.numFormat(Double.parseDouble(words)));
                    }
                } else {
                    texNeedPay.setText("");
                }*/
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.btn_common_red://确认充值
                if (TextUtils.isEmpty(mEtMoney.getText().toString().trim()) && rechargeIndex == -1) {
                    toast(getString(R.string.pls_select_recharge_money));
                    return;
                }

                String pay_money = mEtMoney.getText().toString().trim();
                double money;
                if (TextUtils.isEmpty(pay_money)) {
                    money = Double.parseDouble(integralObjects.get(rechargeIndex).getRechargeAmount());
                } else {
                    money = Double.parseDouble(pay_money);
                }

                if (money <= 0) {
                    toast("充值金额要大于0！");
                    return;
                }

                //type	是	string	支付类型。1支付宝，2微信
                String type = isWXPay ? "2" : "1";
                if (isWXPay && !AppUtils.checkInstallWeiXin(iwxapi, RechargeIntegralActivity.this)) {
                    ToastUtil.showToast(RechargeIntegralActivity.this, "未发现该手机中安装微信客户端！");
                    return;
                }
                LoadingUtils.createLoadingDialog(RechargeIntegralActivity.this, "正在充值...", false);
                createPreOrder(money, type);
                break;
            case R.id.alipay_layout://选择支付宝支付方式
                isWXPay = false;
                alipayImg.setImageResource(R.mipmap.pay_selected_icon);
                wxpayImg.setImageResource(R.mipmap.pay_normal_icon);
                break;
            case R.id.wxpay_layout://选择微信支付方式
                isWXPay = true;
                alipayImg.setImageResource(R.mipmap.pay_normal_icon);
                wxpayImg.setImageResource(R.mipmap.pay_selected_icon);
                break;
            case R.id.title_rigth_image:
                //查看积分充值记录
                RechargeRecordActivity.jump(RechargeIntegralActivity.this);
                break;
        }

    }

    /**
     * 生成微信预订单，并且根据订单信息去微信支付
     */

    private void createPreOrder(double money, String type) {
        PayPresenter.getInstance().createPreOrder(money, type, new DataResponseListener<CreatePreOrderBean>() {
            @Override
            public void onSuccess(CreatePreOrderBean bean) {
                mPreOrderBean = bean;
                if (isWXPay) {//微信支付
                    PayReq request = new PayReq();
                    request.appId = bean.appid;//appId
                    request.partnerId = bean.partnerid;//微信支付分配的商户号
                    request.prepayId = bean.prepayid;//预支付交易会话
                    request.packageValue = bean.packages;
                    request.nonceStr = bean.noncestr;//随机字符串
                    request.timeStamp = bean.timestamp;//时间戳
                    request.sign = bean.sign;//签名
                    request.extData = "app data"; // optional
                    iwxapi.sendReq(request);
                } else {//支付宝支付
                    Message message = new Message();
                    message.what = 0;
                    Bundle bundle = new Bundle();
                    bundle.putString("data", bean.aliPayOrderStr);
                    message.setData(bundle);
                    handler.sendMessage(message);//通知支付宝开始充值
                }
            }

            @Override
            public void onFail(String failMessage) {
                toast(failMessage);
                LoadingUtils.closeDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                toast(R.string.network_or_server_exception);
                LoadingUtils.closeDialog();
            }
        });
    }

    private void searchRecharge() {
        LoadingUtils.createLoadingDialog(this, "", false);
        integralObjects.clear();
        HttpPay.searchRechage(new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                LoadingUtils.closeDialog();
                String result = new String(responseBody);
                Log.e("积分规则查询", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optInt("result") == 100 && jsonObject.optInt("errcode") == 0) {
                        JSONObject dataObject = jsonObject.optJSONObject("data");
                        JSONArray infoArray = dataObject.optJSONArray("info");
                        if (infoArray != null) {
                            for (int i = 0; i < infoArray.length(); i++) {
                                JSONObject intagral = infoArray.optJSONObject(i);
                                IntegralObject integralObject = new IntegralObject();
                                integralObject = JSON.parseObject(intagral.toString(), IntegralObject.class);
                                integralObjects.add(integralObject);
                            }
                            showIntegral();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                LoadingUtils.closeDialog();
            }
        });
    }

    /**
     * 用户信息接口监听
     */
    AsyncHttpResponseHandler resposeUser = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
            LoadingUtils.closeDialog();
            String result = new String(bytes);
            try {
                JSONObject jsonObject = new JSONObject(result);
                String msg = jsonObject.optString("msg");
                if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                    JSONObject dataObject = jsonObject.optJSONObject("data");
                    JSONObject userInfo = dataObject.optJSONObject("userInfo");
                    remainMoney = userInfo.optString("balance");
                    texRemainMoney.setText(remainMoney + "");
                    moneylayout.setVisibility(View.VISIBLE);
                } else {
                    moneylayout.setVisibility(View.GONE);
                    toast(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(context.getString(R.string.network_or_server_exception));
            LoadingUtils.closeDialog();
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0://唤醒支付宝支付
                    String data = msg.getData().getString("data");
                    AliPayUtils.payV2(RechargeIntegralActivity.this, data, handler);
                    break;
                case 1: {//支付结果
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    Log.e("msp验证结果", resultInfo.toString());
                    if (TextUtils.equals(resultStatus, "9000")) {
                        String apliPayResult = resultInfo.toString();
                        Log.e("msp验证结果", "支付成功1" + apliPayResult);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        HttpUserCenter.getUserInfo(null, resposeUser);
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case 3:
                    Toast.makeText(context, "充值成功！", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

}
